<?php
require 'includes/config.php';
require 'includes/auth.php';
require 'includes/sanitize.php';
$data = sanitize($_GET);
$msg = "";
if(isset($data['leagueid'])){
	// Request json with all teams ordered by points
	$request = new makeRequest($backend.'api.php?method=leaguescoreboard&id='.$data['leagueid'], 'GET');
	$tmp = $request->makeRequest();
	$rbody = $tmp[0];
	$obj = json_decode($rbody);
	$http_code = $tmp[1];
	// Check so there is no errors
	if($http_code == 200 && $obj[0]->{'id'} != ""){
		// Beginning of the table
		$msg.="<table border='1'><tr>
			<th>Standing</th>
			<th>Points</th>
			<th>Owner</th>
			<th>Bank</th>
			<th>Drafts</th>
			<th>LW</td>
			<th>CE</th>
			<th>RW</th>
			<th>LD</th>
			<th>RD</th>
			<th>G</th>
			</tr>";
		$i = 0;
		foreach($obj as &$value){
			// Keep track of standing
			$i++;
			// Resolv owner id to username
			$request = new makeRequest($backend.'api.php?method=user&id='.$value->{'owner'}, 'GET');
			$tmp = $request->makeRequest();
			$rbody = $tmp[0];
			$obj2 = json_decode($rbody);
			$http_code = $tmp[1];
			if($http_code == 200){
				// Add standing, points, name and owner to table
				$msg.="<tr>
			<td>".$i."</td>
			<td>".$value->{'points'}."</td>
			<td>".$obj2[0]->{'username'}."</td>
			<td>".$value->{'bank'}."</td>
			<td>".$value->{'drafts'}."</td>";
				// Add all player ids to array
				$playerids= array($value->{'lw'},$value->{'ce'},$value->{'rw'},$value->{'rd'},$value->{'ld'},$value->{'gk'});
				// Resolv all ids in array to player names
				foreach($playerids as &$value2){
					// Request playerinfo
					$request = new makeRequest($backend.'api.php?method=player&id='.$value2, 'GET');
					$tmp = $request->makeRequest();
					$rbody = $tmp[0];
					$http_code = $tmp[1];
					$obj2 = json_decode($rbody);
					// Insert player name into the table (as a link)
					$msg.= "<td><a href='viewplayers.php?playerid=".$value2."'>".$obj2[0]->{'firstname'}." ".$obj2[0]->{'lastname'}."</a></td>";
				}
				$msg.= "</tr>";
			}
		}
		$msg.="</table>";
	}
}else{
	$msg = "You need to specify a league id";
}
require 'includes/header.php';
require 'includes/topmenu.php';
echo '<div id="kaka">';
require 'includes/sidemenu.php';
echo '<div id="content">';
if($msg!=""){
	echo $msg;
}else{
	echo "Something went wrong, please try again later";
}
echo '<div id="info">';
echo '</div>';
require 'includes/footer.php';
?>

</body>
</html>
